package com.phoenix.filemanager;

import java.io.File;
import java.util.ArrayList;

import com.phoenix.Ulties.FileManagerConstants;
import com.phoenix.Ulties.FileManagerUlties;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class FileManagerDetailActivity extends Activity {
	// arraylist parameter
	private ArrayList<String> list_file_sdcard;
	//listview parameter

	private GridView grid_view;
	private AlertDialog.Builder alertlistDialog;

	private LinearLayout ln_layout;
	private static String path;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_file_manager_main);
		if ((GridView)findViewById(R.id.grid_view)!=null) {
			grid_view = (GridView)findViewById(R.id.grid_view);
		}
		if ((LinearLayout)findViewById(R.id.ln_layout)!=null) {
			ln_layout = (LinearLayout)findViewById(R.id.ln_layout);
		}
		//				check sdcard is ready
		if (FileManagerUlties.isStorageAvailable()==true) {
			list_file_sdcard = new ArrayList<String>();

			path = getIntent().getExtras().getString(FileManagerConstants.PathLink);
			if (!path.equals("")) {

				Boolean is_folder = FileManagerUlties.isDirectory(path);
				if (is_folder==true) {
					Boolean folder_emty = FileManagerUlties.isDirectoryEmty(path);

					if (folder_emty==true) {
						list_file_sdcard = FileManagerUlties.isListFilePath(path);
					}
				}
			}
			if (list_file_sdcard.size()>0) {
				//						sort by name
				list_file_sdcard= FileManagerUlties.sortByName(list_file_sdcard);
				//						
				grid_view.setAdapter(new FileManageBaseAdapter(getBaseContext(),path,list_file_sdcard));

				grid_view.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						// TODO Auto-generated method stub
						String name_file = list_file_sdcard.get(arg2);
						path = path+"/"+name_file;
						Boolean is_folder = FileManagerUlties.isDirectory(path);
						//								check in folder
						if (is_folder==true) {
							Intent intent = new Intent(FileManagerDetailActivity.this,FileManagerDetailActivity.class);
							intent.putExtra(FileManagerConstants.PathLink, path);
							startActivity(intent);									
						}
						else 
						{
							if (FileManagerUlties.isImageFile(list_file_sdcard.get(arg2))==true) {

								Intent intent = new Intent();
								intent.setAction(Intent.ACTION_VIEW);
								intent.setDataAndType(Uri.parse("file://" + path), "image/*");
								startActivity(intent);
							}
							else if (FileManagerUlties.isInstallFile(list_file_sdcard.get(arg2))==true) {
								Intent intent =new Intent();
								intent.setAction(Intent.ACTION_VIEW);
								intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");
								startActivity(intent);
							}
						}
					}
				});
				//				set long press onitem
				grid_view.setOnItemLongClickListener(new OnItemLongClickListener() {
					@Override
					public boolean onItemLongClick(AdapterView<?> arg0,
							View arg1, final int arg2, long arg3) {
						// TODO Auto-generated method stub
						alertlistDialog=new AlertDialog.Builder(FileManagerDetailActivity.this);
						alertlistDialog.setTitle(FileManagerConstants.MobileSystem).setItems(FileManagerConstants.items, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								dialog.dismiss();
								actionTouch(arg2,which);
							}
						});
						alertlistDialog.show();
						return false;
					}
				});
			}
			//				Linner layout set on click
			//					grid_view.setOnLongClickListener(new OnLongClickListener() {
			//						
			//						@Override
			//						public boolean onLongClick(View v) {
			//							// TODO Auto-generated method stub
			//							
			//							alertlistDialog=new AlertDialog.Builder(FileManagerDetailActivity.this);
			//							alertlistDialog.setTitle(FileManagerConstants.MobileSystem).setItems(FileManagerConstants.items, new DialogInterface.OnClickListener() {
			//								@Override
			//								public void onClick(DialogInterface dialog, int which) {
			//									// TODO Auto-generated method stub
			//									dialog.dismiss();
			//								}
			//							});
			//							alertlistDialog.show();
			//							
			//							return false;
			//						}
			//					});

		}
	}
	private void actionTouch(final int position,int which) {

		switch (which) {
		case 0:
		{
			//					Copy action
			String file_name =path + "/"+list_file_sdcard.get(position);
			copyFileSDcard(file_name,list_file_sdcard.get(position));

			break;
		}
		case 1:
		{
			String file_name =path + "/"+list_file_sdcard.get(position);

			if (FileManagerUlties.isDirectory(file_name)==true) {
				FileManagerUlties.deleteFolder(file_name);				
			}
			else
			{
				FileManagerUlties.deleteFile(file_name);
			}
			Intent intent = new Intent(FileManagerDetailActivity.this,FileManagerDetailActivity.class);
			intent.putExtra(FileManagerConstants.PathLink, path);
			startActivity(intent);									

			finish();
			break;
		}
		case 2:
		{
			//					Rename action
			AlertDialog.Builder editalert = new AlertDialog.Builder(this);
			editalert.setTitle("Rename File");
			final EditText input = new EditText(this);
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.FILL_PARENT,
					LinearLayout.LayoutParams.FILL_PARENT);
			input.setLayoutParams(lp);
			editalert.setView(input);
			input.setText(list_file_sdcard.get(position));
			editalert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {

					String tmp_file_name = input.getText().toString();
					if (!tmp_file_name.equals("")) {

						String old_name =path + "/"+list_file_sdcard.get(position);
						String new_name= path+ "/"+tmp_file_name;
						FileManagerUlties.renameFileSDCard(old_name, new_name);


						Intent intent = new Intent(FileManagerDetailActivity.this,FileManagerDetailActivity.class);
						intent.putExtra(FileManagerConstants.PathLink, path);
						startActivity(intent);									
						finish();
					}
				}
			});
			editalert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub

				}
			});

			editalert.show();

			break;
		}
		default:
			break;
		}
	}
	public void copyFileSDcard(String file_name,String name)
	{
		SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
		SharedPreferences.Editor editor = preferences.edit();
		editor.putString(FileManagerConstants.KeyCopy, file_name);
		editor.putString(FileManagerConstants.KeyName, name);
		editor.commit();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_file_manager_main, menu);
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.menu_settings:
	        		
	        	SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
	        	String path_file_copy = preferences.getString(FileManagerConstants.KeyCopy,"name");
	        	String name_file_copy = preferences.getString(FileManagerConstants.KeyName,"name");
	        	if (!name_file_copy.equals("name")) {
	        		
	        		File dest  = new File(path+"/"+name_file_copy);
	        		File scr = new File(path_file_copy);
	        		FileManagerUlties.copyFile(scr, dest);
	        	}
				Intent intent = new Intent(FileManagerDetailActivity.this,FileManagerDetailActivity.class);
				intent.putExtra(FileManagerConstants.PathLink, path);
				startActivity(intent);									
				finish();
	        	return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	    
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			String[] tmp_path = path.split("/");
			path="";
			if (tmp_path.length>0) {
				for (int i = 0; i < tmp_path.length; i++) {
					if (i==0) {
						path=path+tmp_path[i];
					}
					else if ((i<tmp_path.length-1)&&(tmp_path.length-1>0)) {
						path=path+"/"+tmp_path[i];
					}
				}
			}
		}
		return super.onKeyDown(keyCode, event);
	}
}
